'use strict';
const DB = require("../pgsql"), crypto = require('crypto'), ld = require("../loadByData")
module.exports = (request, response, rfun)=>{
    switch(request.GET.pathname){
        case "/partners.jsp":{
            response.statusCode = 302;
            response.setHeader("location", "/become-partner.jsp");
            response.end();
            break;
        }case "/":
        case "/index.html":{
            if(request.SESSION.userid > 0){
                response.DATA = {"user":`<div class="username-box">
                <font><a href="/api/v1/center?languagetype=zh_cn">${request.SESSION.un}</a>
                </font>
                <div class="backto-center">进入账户中心<em>ä¸è§</em></div>
            </div>
            <a href="/api/v1/logout?backurl=/index.html&languagetype=zh_cn" class="log-out">退出</a>`}
            }else{
                response.DATA = {"user":'<a  href="/login.html?backurl=/index.html&languagetype=zh_cn" class="login">登录</a><a href="/regist.jsp?backurl=/index.html&amp;languagetype=zh_cn" class="regist">注册</a>'}
            }
            ld(request, response, rfun);
            break;
        }case "/api/v1/center":
        case "/game/v3/main.jsp":
        case "/game/pages/main.jsp":
        case "/product-game.jsp":{
            if(!request.SESSION.userid){
                response.statusCode = 302;
                response.setHeader("location", "/");
                response.end();
                return;
            }
            response.DATA = {"username":request.SESSION.un};
            ld(request, response, rfun);
            break;
        }case "/game":{
            response.statusCode = 302;
            response.setHeader("location", "/game/");
            response.end();
            break;
        }case "/game/":{
            response.statusCode = 302;
            response.setHeader("location", "/game/v3/main.jsp");
            response.end();
            break;
        }case "/api/v1/checkEmail":{ //检查账号
            let email = Buffer.from(request.POST.email, 'base64').toString();
            DB.exeSql(`select userid from users where username=$1`,(ret)=>{
                if(ret.rows[0] && ret.rows[0].userid > 0){
                    response.DATA = {"code":200,"message":true};
                }else{
                    response.DATA = {"code":200,"message":false};
                }
                rfun();
            },[email])
            break;
        }case "/api/v1/checkRegisterTelephone":{ //检查手机号暂不支持
            response.end('{"code":200,"message":false}');
            break;
        }case "/api/v1/checkVerificationCodeAndRegist":{ //注册
            let pass = Buffer.from(request.POST.password, 'base64').toString();
            let md5 = crypto.createHash('md5');
            md5.update(pass);
            pass = md5.digest('hex');
            DB.exeSql(`insert into users(username,passwords,ctime,phone) values($1,$2,NOW(),$3) RETURNING *`,(ret)=>{
                response.DATA = {"success":true};
                request.SESSION['userid'] = ret.rows[0].userid;
                request.SESSION['un'] = ret.rows[0].username;
                rfun();
            },[Buffer.from(request.POST.email, 'base64').toString(),pass,request.POST.registerTelephone])
            break;
        }case "/api/v1/completeExtraUserInfo":{
            //console.log("completeExtraUserInfo", request.POST);
            DB.exeSql(`update users set company=$1,names=$2,duty=$3,qq=$4 where userid=$5`,(ret)=>{
                response.end('1');
            },[request.POST.company,request.POST.userName,request.POST.duty,request.POST.qq,request.SESSION.userid]);
            break;
        }case "/api/v1/login":{ //登录
            response.DATA = {legalFlag:1,canViewFlag:1,success:0,user:{email:request.POST.email,password:request.POST.password}};
            let email = Buffer.from(request.POST.email, 'base64').toString(), password = Buffer.from(request.POST.password, 'base64').toString();
            let md5 = crypto.createHash('md5');
            md5.update(password);
            password = md5.digest('hex');
            DB.exeSql(`select * from users where username=$1 and passwords=$2`,(ret)=>{
                if(ret.rows[0] && ret.rows[0].userid > 0){
                    response.DATA.success = 1;
                    response.DATA.user.registerTelephone = ret.rows[0].phone;
                    //console.log(request.SESSION);
                    request.SESSION['userid'] = ret.rows[0].userid;
                    request.SESSION['un'] = ret.rows[0].username;
                }
                rfun();
            },[email,password]);
            //console.log(email, password);
            //rfun();
            break;
        }case "/game/v1/gamecenter/logout":
        case "/game/api/v3/developer/logout":{ //退出
            for(let k in request.SESSION) delete request.SESSION[k];
            response.end();
            break;
        }case "/api/v1/logout":{
            for(let k in request.SESSION) delete request.SESSION[k];
            response.statusCode = 302;
            response.setHeader("location", "/");
            response.end();
            break;
        }case "/game/api/v3/product/create":{ //创建产品
            if(!request.SESSION.userid){
                response.statusCode = 302;
                response.setHeader("location", "/");
                response.end();
                return;
            }
            let para = [request.SESSION.userid,'',4,request.POST.productype,request.POST.productName]; //console.log(request.POST, para);
            let md5 = crypto.createHash('md5');
            md5.update(request.SESSION.userid+new Date().getTime().toString());
            para[1] = md5.digest('hex').substr(0,16);
            DB.exeSql(`insert into app(userid,appkey,createstep,productype,productname,ctime) values($1,$2,$3,$4,$5,NOW()) RETURNING *`,(ret)=>{
                response.DATA = {"val":{"currency":"CNY","timeZone":8,"comefrom":0,"productName":ret.rows[0].productname,"createStep":ret.rows[0].createstep,"productId":ret.rows[0].productid,"debugId":44755,"registerTime":null,"developerId":ret.rows[0].userid,"registerTimeStr":"","hasDataDate":0,"isdeleted":false,"totalChargeSum":0.0,"todayChargeSum":0.0,"totalInstallNum":0,"todayInstallNum":0,"totalRegisterNum":0,"todayRegisterNum":0,"totalStartupNum":0,"todayStartupNum":0,"curProCreator":false,"currencyDisplay":null,"playerMark":0,"logo":null,"platformId":0,"productype":ret.rows[0].productype,"productypeName":"卡牌游戏","sequencenumber":ret.rows[0].appkey,"platformList":null},"code":200};
                rfun();
            },para);
            break;
        }case "/game/v1/gamecenter/updateProduct":{ //修改产品
            if(!request.SESSION.userid){
                response.statusCode = 302;
                response.setHeader("location", "/");
                response.end();
                return;
            }
            let para = [request.SESSION.userid,request.POST.productId,request.POST.productype,request.POST.productName]; //console.log(request.POST, para);
            DB.exeSql(`update app set productype=$3,productname=$4 where userid=$1 and productid=$2 RETURNING *`,(ret)=>{
                response.DATA = {"val":{"currency":"CNY","timeZone":8,"comefrom":0,"productName":ret.rows[0].productname,"createStep":ret.rows[0].createstep,"productId":ret.rows[0].productid,"debugId":44755,"registerTime":null,"developerId":ret.rows[0].userid,"registerTimeStr":"","hasDataDate":0,"isdeleted":false,"totalChargeSum":0.0,"todayChargeSum":0.0,"totalInstallNum":0,"todayInstallNum":0,"totalRegisterNum":0,"todayRegisterNum":0,"totalStartupNum":0,"todayStartupNum":0,"curProCreator":false,"currencyDisplay":null,"playerMark":0,"logo":null,"platformId":0,"productype":ret.rows[0].productype,"productypeName":"卡牌游戏","sequencenumber":ret.rows[0].appkey,"platformList":null},"code":200};
                rfun();
            },para);
            break;
        }case "/game/v1/gamecenter/fetchProductById":{ //获取指定产品
            DB.exeSql(`select * from app where userid=$1 and productid=$2`,(ret)=>{
                if(ret.rows[0]){
                    response.DATA = {"currency":"CNY","timeZone":0,"isdeleted":false,"totalChargeSum":0.0,"todayChargeSum":0.0,"totalInstallNum":0,"todayInstallNum":0,"totalRegisterNum":0,"todayRegisterNum":0,"totalStartupNum":0,"todayStartupNum":0,"curProCreator":false,"currencyDisplay":null,"hasDataDate":0,"playerMark":0,"logo":null,"productName":ret.rows[0].productname,"createStep":ret.rows[0].createstep,"comefrom":0,"productId":ret.rows[0].productid,"sequencenumber":ret.rows[0].appkey,"productype":ret.rows[0].productype,"productypeName":"卡牌游戏","platformId":0,"registerTime":ret.rows[0].ctime.getTime(),"developerId":ret.rows[0].userid,"registerTimeStr":request.PUBFUN.getdatestr("Ymd",0,0,ret.rows[0].ctime),"debugId":0,"platformList":[]};
                }else response.DATA = {};
                rfun();
            },[request.SESSION.userid,request.GET.query.productId])

            break;
        }case "/game/api/v3/product/allProductsBasic":{ //产品列表
            DB.exeSql(`select * from app where userid=$1`,(ret)=>{
                response.DATA = [];
                for(let i=0;i<ret.rows.length;i++){
                    response.DATA.push({"revenueNum":0.0,"installNum":0,"newPlayerNum":0,"oldPlayerNum":0,"debugId":ret.rows[i].productid,"currency":"CNY","productName":ret.rows[i].productname,"createStep":ret.rows[i].createstep,"menuInfo":null,"productId":ret.rows[i].productid,"sequencenumber":ret.rows[i].appkey,"productype":ret.rows[i].productype,"productypeName":"卡牌游戏","createTime":ret.rows[i].ctime.getTime(),"privilegeBean":null,"ownership":"OWNER","platformList":null});
                }
                rfun();
            },[request.SESSION.userid]);
            break;
        }case "/game/api/v3/product/allProductsInfo":{ //产品信息
            DB.exeSql(`select * from app where userid=$1 and productid=$2`,(ret)=>{
                if(ret.rows){
                    response.DATA = {"revenueNum":0.0,"installNum":0,"oldPlayerNum":0,"revenueCNYNum":0.0,"platformList":"","debugId":ret.rows[0].productid,"productId":ret.rows[0].productid,"newPlayerNum":0};
                    request.SESSION[ret.rows[0].productid] = ret.rows[0].appkey;
                }
                rfun();
            },[request.SESSION.userid,request.POST.productId]);
            break;
        }case "/game/v1/gamecenter/fetchProductAndPlatforms":{ //后台用于显示产品列表
            DB.exeSql(`select * from app where userid=$1`,(ret)=>{
                response.DATA = [];
                for(let i=0;i<ret.rows.length;i++){
                    response.DATA.push({"productid":ret.rows[i].productid,"productName":ret.rows[i].productname,"registerTime":ret.rows[i].ctime.getTime(),"platformList":[1,2,3]});
                }
                rfun();
            },[request.SESSION.userid]);
            break;
            break;
        }
    }
}